﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco;
using umbraco.NodeFactory;
using umbraco.cms.businesslogic.media;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
using System.Xml;

namespace ScDataTypes.DataTypes
{

    [ToolboxData("<{0}:MediaTreeviewDropDownList runat=server></{0}:MediaTreeviewDropDownList>")]
    public class MediaTreeviewDropDownList : BaseTreeviewDropDownListControl
    {
        
        #region Properties

        /// <summary>
        /// Comma seperated string containing the numberic ids of all selected nodes value1,value2,value3
        /// </summary>
        public new string Selected
        {
            get
            {
                return base.Selected;
            }
            set
            {
                // Ensure controls are created
                this.EnsureChildControls();

                // Loop through all node ids
                this.AddMedia(value);
            }
        }

        /// <summary>
        /// Allowed document types
        /// </summary>
        public string MediaType
        {
            get { return this.ToStr(ViewState["MediaType"]); }
            set { ViewState["MediaType"] = value; }
        }

        /// <summary>
        /// Inital path to the root node
        /// </summary>
        public string Location
        {
            get { return this.ToStr(ViewState["Location"]); }
            set { ViewState["Location"] = value; }
        }

        #endregion

        #region Media Functions

        /// <summary>
        ///  Get the initial starting node
        /// </summary>
        /// <returns></returns>
        Media[] GetInitalMediaItems()
        {
            try
            {
                // Get inital node
                if (this.Location.Length != 0 &&
                    umbraco.helper.IsNumeric(this.Location))
                {
                    Media objMedia = new Media(Convert.ToInt32(this.Location));
                    if (objMedia != null && objMedia.Id == Convert.ToInt32(this.Location))
                        return new Media[] { objMedia };
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            return Media.GetRootMedias();
        }

        /// <summary>
        /// Add node to selected listbox providing it doesn't already exist
        /// </summary>
        /// <param name="NodeId">String containing the numberic node id</param>
        void AddMedia(string MediaId)
        {
            try
            {
                if (umbraco.helper.IsNumeric(MediaId))
                {
                    if (MediaId == "0")
                    {
                        base.TextBox.Text = string.Empty;
                        base.Selected = string.Empty;
                    }
                    else
                    {
                        // Find node in umbraco and add to listbox from the database to ignore issues with
                        // unpublished nodes
                        Media objMedia = new Media(Convert.ToInt32(MediaId));

                        if ((objMedia != null && objMedia.Id != 0) &&
                            (
                                this.MediaType == string.Empty || string.Compare(this.MediaType, objMedia.ContentType.Alias) == 0
                            ))
                        {
                            base.TextBox.Text = objMedia.Text;
                            base.Selected = objMedia.Id.ToString();
                        }
                    }
                }
            }
            catch
            {
            }
        }

        #endregion

        #region TreeView Functions

        /// <summary>
        /// Populate treenode event
        /// </summary>
        protected override void PopulateTreeView(TreeNodeEventArgs e)
        {
            Media objMedia = new Media(Convert.ToInt32(e.Node.Value));

            // Check for child nodes
            if (objMedia != null &&
                objMedia.Id != 0 &&
                objMedia.ChildCount != 0)
                this.PopulateTreeviewFromMedia(e.Node, objMedia);
        }

        /// <summary>
        /// Populate nodes on a TreeNode my matching it to the Node.Children
        /// </summary>
        /// <param name="TreeNode">TreeNode that requires to be populated</param>
        /// <param name="Node">Node to use to copy Node.Children from</param>
        void PopulateTreeviewFromMedia(TreeNode TreeNode, Media Media)
        {
            foreach (Media objMedia in Media.Children)
            {
                TreeNode objTreeNode = new TreeNode();

                // Node properties
                objTreeNode.Text = objMedia.Text;
                objTreeNode.Value = objMedia.Id.ToString();
                objTreeNode.Expanded = false;

                // Expanding nodes
                if (objMedia.ChildCount != 0)
                    objTreeNode.PopulateOnDemand = true;
                else
                    objTreeNode.PopulateOnDemand = false;

                // Image
                if (objMedia.ContentType.IconUrl.StartsWith("."))
                    objTreeNode.ImageUrl = ImagePath + "folder.gif";
                else
                    objTreeNode.ImageUrl = ImagePath + objMedia.ContentType.IconUrl;

                // Add treenode
                TreeNode.ChildNodes.Add(objTreeNode);
            }
        }

        #endregion

        #region Child Controls

        /// <summary>
        /// Child control all created and treeview setup
        /// </summary>
        protected override void ChildControlsCreated()
        {
            this.SelectionChanged += new SelectionChangedDelegate(MediaTreeviewDropDownList_SelectionChanged);

            if (!this.Page.IsPostBack)
            {
                // Inital node
                foreach (Media objMedia in this.GetInitalMediaItems())
                {
                    // Setup node
                    TreeNode objTreeNode = new TreeNode();
                    objTreeNode.Text = (objMedia.Text != string.Empty && objMedia.Text != "-1" ? objMedia.Text : "Media Library");
                    objTreeNode.Value = objMedia.Id.ToString();
                    objTreeNode.ImageUrl = ImagePath + "folder.gif";
                    objTreeNode.Expanded = false;

                    // Add inital node children
                    this.PopulateTreeviewFromMedia(objTreeNode, objMedia);

                    // Add root node to treeview
                    this.TreeView.Nodes.Add(objTreeNode);
                }
            }
        }

        #endregion

        #region Postback Events

        void MediaTreeviewDropDownList_SelectionChanged(object sender, EventArgs e)
        {
            this.AddMedia(this.TreeView.SelectedValue);
        }

        #endregion

    }

}
